MySQL - Data Binding - ASP.Net

With ASP.NET, databinding is a big thing, and once you have used it, you will probably understand why the databinding really can save some time for you. We will start with a very basic example of databinding , but even if it is simple, it is also very useful. Preparing a dropdown list can be a boring task, but it is easy to see how easy it can be. Get started by adding a dropdown list to the page:


<asp:DropDownList runat="server" id="ddlUsers" datavaluefield="id" datatextfield="name" />

DataValuefield property tells the control of which database field should be used for the value of each item, and Datatteffield tells that control which items can be used for the actual text. We need this in the markup section, so switch to CodeBhind. Here we will use almost the same code in the last chapter, which will be a small revision:


try
{
    using(OdbcConnection connection = new OdbcConnection(ConfigurationManager.ConnectionStrings["MySQLConnStr"].ConnectionString))
    {
        connection.Open();
        using(OdbcCommand command = new OdbcCommand("SELECT id, name FROM test_users", connection))
        using(OdbcDataReader dr = command.ExecuteReader())
        {
            ddlUsers.DataSource = dr;
            ddlUsers.DataBind();
            dr.Close();
            
        }
        connection.Close();
    }
}
catch(Exception ex)
{
    Response.Write("An error occured: " + ex.Message);
}

Only two things have changed from the previous example: We've added a field for the query (id field), and we have changed the loop to some databasing lines before our dropdown list determines the voters of our davatarsa, and The second downdown asks the list to be databases. This is what we need, that you will see if you run the website. The dropdown list will be filled with names from our test table.

This is just a basic example. Later, when we work with repeaters, datagrids etc. you will definitely realize the real potential of databasing.